package com.wxy.favorites.config;

import com.wxy.favorites.entity.User;
import com.wxy.favorites.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author e-Xiaoyuan.Wang
 * @since 2022/12/7 19:33
 */
@Component
@Slf4j
public class InitConfig implements CommandLineRunner {

    @Value("${user.account}")
    private String userAccount;

    @Value("${user.password}")
    private String userPassword;

    @Value("${admin.account}")
    private String adminAccount;

    @Value("${admin.password}")
    private String adminPassword;

    @Autowired
    private AppConfig appConfig;

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public void run(String... args) throws Exception {
        Path repository = Paths.get(appConfig.getFileRepository());
        if (!Files.exists(repository) && Files.exists(Files.createDirectory(repository))) {
            log.info("创建文件仓库：repository = {}", repository.toAbsolutePath());
        }
        // 初始化用户账号
        User demo = userService.findByUsername(userAccount);
        if (demo == null) {
            User user = userService.save(new User().setNickName("演示账号").setEmail("demo@qq.com").setUsername(userAccount)
                    .setPassword(passwordEncoder.encode(DigestUtils.md5DigestAsHex(userPassword.getBytes(StandardCharsets.UTF_8))))
                    .setCapacity(appConfig.getInitCapacity() * 1024 * 1024L).setRegisterTime(new Date()));
            log.info("初始化用户：account = {}, password = {}", userAccount, userPassword);
            userService.initData(user.getId());
        }
        // 初始化管理员账号
        User admin = userService.findByUsername(adminAccount);
        String md5 = DigestUtils.md5DigestAsHex(adminPassword.getBytes(StandardCharsets.UTF_8));
        if (admin == null) {
            User user = userService.save(new User().setIsAdmin(1).setNickName("超级管理员").setEmail("admin@qq.com")
                    .setUsername(adminAccount).setPassword(passwordEncoder.encode(md5)).setRegisterTime(new Date()));
            log.info("初始化管理员：account = {}, password = {}", adminAccount, adminPassword);
            userService.initData(user.getId());
        } else {// 同步超管密码
            if (!passwordEncoder.matches(md5, admin.getPassword())) {
                admin.setPassword(passwordEncoder.encode(md5));
                userService.update(admin);
                log.info("修改管理员：account = {}, password = {}", adminAccount, adminPassword);
            }
        }
    }
}
